#include "usart3.h"
#include "timer0.h"
#include <stdarg.h>
#include <stdio.h>

/* USART RX Port/Pin definition */
#define USART3_RX_PORT                   (PortB)
#define USART3_RX_PIN                    (Pin13)
#define USART3_RX_FUNC                   (Func_Usart3_Rx)

/* USART TX Port/Pin definition */
#define USART3_TX_PORT                   (PortB)
#define USART3_TX_PIN                    (Pin12)
#define USART3_TX_FUNC                   (Func_Usart3_Tx)
	
int fputc(int ch, FILE *f) {
	while((M4_USART3->SR & (1<<7))==0){;}
	M4_USART3->DR_f.TDR = (uint8_t)ch;
	return (uint8_t)(ch);
}

void USART3_Init(u32 baud){
	uint16_t u16RxData;
	stc_irq_regi_conf_t stcIrqRegiCfg;
	en_result_t enRet = Ok;
	const stc_usart_uart_init_t stcInitCfg = {
		UsartIntClkCkNoOutput,
		UsartClkDiv_1,
		UsartDataBits8,
		UsartDataLsbFirst,
		UsartOneStopBit,
		UsartParityNone,
		UsartSampleBit8,
		UsartStartBitFallEdge,
		UsartRtsEnable,
	};
	PWC_Fcg1PeriphClockCmd(PWC_FCG1_PERIPH_USART3, Enable);
	PORT_SetFunc(USART3_RX_PORT, USART3_RX_PIN, USART3_RX_FUNC, Disable);
	PORT_SetFunc(USART3_TX_PORT, USART3_TX_PIN, USART3_TX_FUNC, Disable);
	enRet = USART_UART_Init(M4_USART3, &stcInitCfg);
	if (enRet != Ok){
		while (1);
	}
    enRet = USART_SetBaudrate(M4_USART3, baud);
    if (enRet != Ok){
        while (1);
    }
    USART_FuncCmd(M4_USART3, UsartRx, Disable);
    USART_FuncCmd(M4_USART3, UsartTx, Enable);
	USART_FuncCmd(M4_USART3, UsartRxInt, Disable);
}
